<script lang="ts">
import {mapState} from "vuex";
import Vue from "vue";
import tips from "@/utils/tips";
import CustomNavBar from "@/components/CustomNavBar/CustomNavBar.vue";
import TabBar from "@/components/TabBar/TabBar.vue";
import {getSnTicket} from "@/services/miniApp";
import NavBar from "@/components/nav-bar/nav-bar.vue";

export default Vue.extend({
  components: {NavBar, CustomNavBar, TabBar},

  data() {
    return {
      tabCells: [{
        path: '/pages/store/index',
        title: 'store_manage'
      }, {
        path: '/pages/select_store/select_store',
        title: 'select_store'
      }, {
        path: '/pages/order/order',
        title: 'order'
      }],

      bannerList: [
        {image: 'https://img0.baidu.com/it/u=1790104919,3555575748&fm=253&fmt=auto&app=138&f=JPEG?w=751&h=500'},
        {image: 'https://img0.baidu.com/it/u=1790104919,3555575748&fm=253&fmt=auto&app=138&f=JPEG?w=751&h=500'},
        {image: 'https://img0.baidu.com/it/u=1790104919,3555575748&fm=253&fmt=auto&app=138&f=JPEG?w=751&h=500'},
        {image: 'https://img0.baidu.com/it/u=1790104919,3555575748&fm=253&fmt=auto&app=138&f=JPEG?w=751&h=500'},
        {image: 'https://img0.baidu.com/it/u=1790104919,3555575748&fm=253&fmt=auto&app=138&f=JPEG?w=751&h=500'},
      ],

      cell: [
        //   {
        //     title: 'function',
        //   }, {
        //     title: 'folder',
        //   }, {
        //     title: 'feedback',
        //   },
        {
          title: 'service',
          openType: 'contact'
        },
        // {
        //   title: 'info',
        // },
        // {
        //   title: 'settings',
        // }
      ],
      tmplIds: ['P8dvF3I3i6waJ4mAmJgbuM7TkyrTsh9ZmBloRQEgg60', 'RV8ydAR61hDn599EvQB2HQLugd7bXQLRXPhNV6ZUy_0', 'aoetMCYI-OH-XEjfFt6-bjUOX_DHRNMXOAZBFIENjJU'],
      isPrompt: false,
    }
  },
  computed: {
    ...mapState(['isLogin', "userInfo"]),
    lang(): any {
      return this.$t('me');
    }
  },
  onLoad() {
    if (!this.isLogin) {
      this.$store.commit('showLogin', true)
    }
  },
  onShow() {
    this.getPromptState()
  },
  methods: {
    getPromptState() {
      const tmplIds = this.tmplIds
      uni.getSetting({
        withSubscriptions: true,
        success: (res) => {
          const {mainSwitch, itemSettings} = res.subscriptionsSetting
          if (mainSwitch && itemSettings != null) {
            this.isPrompt = tmplIds.every(tmplId => itemSettings[tmplId] === 'accept')
          } else {
            this.isPrompt = false
          }
        }
      })
    },
    //跳转页面
    onNavigator(url: string): void {
      if (!url) {
        // tips.toast('بۇ ئىقتىدار ۋاقتىنچە ئىتىك')
        return;
      } else if (url === 'store/index') {
        const {is_store} = this.userInfo
        if (is_store === null) {
          console.log('is_store', is_store)
          uni.navigateTo({url: '/pages/store/add_store'})
        } else if (is_store === 0) {
          tips.toast('待审核')
          return;
        } else if (is_store === 1) {
          console.log('is_store', is_store)
          uni.navigateTo({url: `/pages/${url}`});
          return;
        } else if (is_store === 2) {
          tips.toast('请联系客服')
          return;
        }
      } else {
        uni.navigateTo({url: `/pages/${url}`});
      }
    },
    // 点击通知
    onPrompt(event: any) {
      // if (!event) {
      //   uni.openSetting()
      //   return
      // }

      uni.showLoading({title: this.otherLang.loading})
      uni.getSetting({
        withSubscriptions: true,
        success: async (res) => {
          const {mainSwitch, itemSettings} = res.subscriptionsSetting
          // 如果用户没有授权，则直接打开设置页
          if (!mainSwitch) {
            uni.openSetting()
            return
          }
          // 如果用户已经授权，则直接订阅
          if (itemSettings != null) {
            const hasNonAccepted = this.tmplIds.some(tmplId => itemSettings[tmplId] !== 'accept')
            // 如果用户没有订阅全部模板，则订阅全部模板
            if (hasNonAccepted) {
              await this.requestSubscription()
            } else {
              this.isPrompt = true
            }
          } else {
            await this.requestSubscription()
          }
        },
        fail(error) {
          console.log(error)
          uni.hideLoading()
        }
      })
    },
    // 订阅消息
    async requestSubscription() {
      const sn = this.userInfo.openid
      const tmplIds = this.tmplIds
      const modelId = '_FOAueLH5oc72ao8rRH4CQ'
      const {code, msg, data: {sn_ticket}} = await getSnTicket(sn, modelId)

      if (code === 200) {
        uni.requestSubscribeDeviceMessage({
          sn,
          tmplIds,
          modelId,
          snTicket: sn_ticket,
          success: (res) => {
            console.log('订阅消息成功', res)
            const hasNonAccepted = tmplIds.some(tmplId => res[tmplId] !== 'accept')
            if (hasNonAccepted) {
              console.log("hasNonAccepted -=--=", hasNonAccepted)
              // 如果用户没有订阅模板，则打开设置页 , 用户手动订阅打开 (但是打不开设置页)
              uni.openSetting()
            } else {
              this.isPrompt = true
            }
            this.isPrompt = true
          },
          fail: (err) => {
            console.log('订阅消息失败', err)
            this.isPrompt = false
          },
          complete: () => uni.hideLoading()
        })
      } else {
        tips.toast(msg)
      }
    },
  }
})
</script>

<template>
  <view>
    <nav-bar :is-back-icon="false" :page-title="lang.pageName"/>

    <view :class="locale">
      <view class="padding-30">
        <!-- 我的-->
        <view class="flex-between text-32 user-box">
          <view class="flex-center gap-20">
            <view>
              <image class="avatar" :src="userInfo.avatarUrl"/>
            </view>
            <view class="flex-column gap-8">
              <view style="font-weight: 600">{{ userInfo.nickname }}</view>
              <view class="color-grey">UID:{{ userInfo.id }}</view>
            </view>
          </view>

          <!-- 编译-->
          <!--          <view class="center bg-white padding-14 radio-fifty-percent" @click="onNavigator('me/EditUserInfo')"-->
          <!--                hover-class="hover" hover-stay-time="0">-->
          <!--            <u-icon size="26" color="#1073FF" name="edit-pen"/>-->
          <!--          </view>-->
        </view>


        <!-- 商家订单等等-->
        <view class="radio-20 flex-center tab-cell">
          <view v-if="Object.keys(userInfo.agent).length>0" class="column-center gap-20 flex-1" hover-class="hover"
                hover-stay-time="0"
                @click="onNavigator('Agent/Agent')">
            <image :src="`/static/me/agent.svg`" class="icon"/>
            <view class="title">{{ lang['agent'] }}</view>
          </view>
          <view class="column-center gap-20 flex-1" hover-class="hover" hover-stay-time="0"
                @click="onNavigator('store/index')">
            <image :src="`/static/me/store_manage.svg`" class="icon"/>
            <view class="title">{{ lang['store_manage'] }}</view>
          </view>
          <!-- 选择商家-->
          <view class="column-center gap-20 flex-1" hover-class="hover" hover-stay-time="0"
                @click="onNavigator('select_store/select_store')">
            <image :src="`/static/me/select_store.svg`" class="icon"/>
            <view class="title">{{ lang['select_store'] }}</view>
          </view>

          <view class="column-center gap-20 flex-1" hover-class="hover" hover-stay-time="0"
                @click="onNavigator('order/order')">
            <image :src="`/static/me/order.svg`" class="icon"/>
            <view class="title">{{ lang['order'] }}</view>
          </view>
        </view>


        <!-- 功能和文档-->
        <view class="radio-20 flex-column cell">
          <view v-for="(item, index) in cell" :key="index">
            <view class="flex-between padding-20 margin-20" hover-class="hover" hover-stay-time="0"
                  @click="onNavigator(item.path)" style="position: relative">
              <view class="flex-center gap-20">
                <image :src="`/static/me/${item.title}.svg`" class="icon"/>
                <view class="text-32">{{ lang[item.title] }}</view>
              </view>
              <button class="service" :open-type="item.openType"/>
              <view>
                <u-icon :name="arrowIcon" size="20"/>
              </view>
            </view>
          </view>

          <view v-if="userInfo.is_store === 1" class="flex-between padding-20 margin-20">
            <view class="flex-center gap-20">
              <image :src="`/static/me/prompt.svg`" class="icon"/>
              <view class="text-32">{{ lang.promptSettings }}</view>
            </view>
            <view class="ltr">
              <u-switch v-model="isPrompt" color="#1073FF" @change="onPrompt"/>
            </view>
          </view>
        </view>
      </view>
      <tab-bar :current="1"/>
    </view>
  </view>
</template>

<style lang="scss">
.user-box {
  padding: 20rpx;

  .avatar {
    width: 140rpx;
    height: 140rpx;
    border-radius: 50%;
  }
}

.tab-cell {
  background: white;
  padding: 40rpx 0 40rpx 0;
  margin: 20rpx 0 20rpx 0;

  .icon {
    width: 84rpx;
    height: 84rpx;
  }

  .title {
    font-size: 28rpx;
    font-weight: 400;
  }
}

.cell {
  background: white;

  .icon {
    width: 36rpx;
    height: 36rpx;
  }
}
</style>